package com.lsmo.android.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.lsmo.android.carfans.R;

/**
 * DataBase 操作类
 * 
 * @author maxl
 * 
 */
public class DBUtils {

	private static Context context;
	private static String dataBaseName = "carfans_db.sqlite";//数据库名称

	public DBUtils(Context context) {
		this.context = context;
	}

	/**
	 * 操作数据库
	 * 
	 * @param connectionName
	 * @param sql
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public static ResultSet executeQuery(String sql, Object[] parameters)
			throws Exception {
		return getConnection(dataBaseName).executeQuery(sql, parameters);
	}

	public static DBConnection getConnection(String connectionName)
			throws Exception {
		String pathFile = getPath() + connectionName;// 转换目录data下
		initDataBase(pathFile);
		SQLiteDatabase data = SQLiteDatabase.openOrCreateDatabase(pathFile,
				null);
		return new DBConnection(data);
	}

	/**
	 * 获取数据库保存路径，如果存在SD卡，则保存在sd卡中，否则保存在内置存储器中
	 * 
	 * @return
	 */
	public static String getPath() {
		String pathFile = null;
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			pathFile = "/sdcard/carfans/databases/";
			File file = new File(pathFile);
			if (!file.exists()) {
				file.mkdirs();
			}
		} else {
			pathFile = getDBPath();
		}
		return pathFile;
	}

	/**
	 * 获取内存中数据库路径
	 * 
	 * @return
	 */
	public static String getDBPath() {
		String path = context.getApplicationContext().getFilesDir()
				.getAbsolutePath();
		path = path.substring(0, path.lastIndexOf("/"));
		path += "/databases/";
		return path;
	}

	private static void initDataBase(String pathFile) {
		File file = new File(pathFile);
		if (!file.exists()) {
			InputStream is = context.getResources().openRawResource(
					R.raw.carfans_db);
			try {
				FileOutputStream fos = new FileOutputStream(pathFile);

				byte[] buffer = new byte[8192];
				int count = 0;
				while ((count = is.read(buffer)) >= 0) {
					fos.write(buffer, 0, count);
				}
				fos.close();
				is.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}